"""
和文件相关的类定义
"""
import json

from data_define import Record
import os


# 先定义一个抽象类用来做顶层设计，确定有哪些功能需要实现
class FileReader:
    """抽象类，用于读取数据，并将数据转换成Record对象"""
    def read_data(self) -> list[Record]:
        """读取文件的数据，将读到的每一条数据都转换为Record对象，将他们都封装到list内返回即可"""
        pass


class TextFileReader(FileReader):
    def __init__(self, path: str):
        """
        构造函数
        :param path: 数据文件的路径
        """
        self.path = path

    def read_data(self) -> list[Record]:
        """
        复写（实现抽象方法）父类的方法，读取csv格式的数据文件，将其转换为list
        :return: Record对象的list
        """
        result: list[Record] = []
        try:
            f = open(self.path, "r", encoding="UTF-8")
            for line in f.readlines():
                line = line.strip()
                data_list = line.split(",")
                result.append(Record(data_list[0], data_list[1], int(data_list[2]), data_list[3]))
        except Exception as e:
            print(f"读取数据文件失败，错误内容：{e}，错误类型：{type(e)}")
        else:
            f.close()

        return result


class JsonFileReader(FileReader):
    def __init__(self, path: str):
        self.path = path

    def read_data(self) -> list[Record]:
        """
        复写（实现抽象方法）父类的方法，读取json格式的数据文件，将其转换为list
        :return: Record对象的list
        """
        result: list[Record] = []
        try:
            f = open(self.path, "r", encoding="UTF-8")
            for line in f.readlines():
                data_dict = json.loads(line)
                result.append(
                    Record(data_dict["date"], data_dict["order_id"], int(data_dict["money"]), data_dict["province"]))
        except Exception as e:
            print(f"读取数据文件失败，错误内容：{e}，错误类型：{type(e)}")
        else:
            f.close()

        return result


if __name__ == '__main__':
    path_txt = f"{os.getcwd()}/2011年1月销售数据.txt"
    path_json = f"{os.getcwd()}/2011年2月销售数据JSON.txt"
    text_file = TextFileReader(path_txt)
    json_file = JsonFileReader(path_json)
    list1 = text_file.read_data()
    list2 = json_file.read_data()

    for l in list1:
        print(l)
    for l in list2:
        print(l)

